package cn.ecut.dao;

import cn.ecut.exception.DaoException;
import cn.ecut.model.Apply;
import cn.ecut.model.Good;
import cn.ecut.model.User;
import cn.ecut.utils.JDBCHelper;
import cn.ecut.utils.TableNames;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.sql.SQLException;

public class ApplyDao {

    private GoodDao goodDao=new GoodDao();
    private UserDao userDao=new UserDao();
    public Apply loadByApplyId(Integer applyId ){
        String SQL = "select * from " + TableNames.APPLY_TABLE_NAME + " where applyid = ? " ;
        ResultSet resultSet = JDBCHelper.query(SQL, applyId);
        List <Apply> apply = warp(resultSet);
        if( apply.size() > 0 ){
            return apply.get(0) ;
        }
        return null  ;
    }
    public List<Apply> loadByGoodId(Integer applygoodId ){
        String SQL = "select * from " + TableNames.APPLY_TABLE_NAME + " where applygoodid = ? " ;
        ResultSet resultSet = JDBCHelper.query(SQL, applygoodId);
        List <Apply> apply = warp(resultSet);
        return apply;
    }
    public boolean updateApplyState(Integer applyId)
    {
        String SQL="update "+TableNames.APPLY_TABLE_NAME+" set applystate = '1' where applyid= " +applyId;
        return JDBCHelper.execute(SQL);
    }
    public boolean updateApplyState2(Integer applyId)
    {
        String SQL="update "+TableNames.APPLY_TABLE_NAME+" set applystate = '2' where applyid= " +applyId;
        return JDBCHelper.execute(SQL);
    }
    public boolean deleteApply(Integer applyId) {
        String SQL="delete from "+TableNames.APPLY_TABLE_NAME+" where applyid="+applyId;
        return JDBCHelper.execute(SQL);
    }
    private List<Apply> warp(ResultSet resultSet) {
        List<Apply> list = new ArrayList<>();
        try{
            while (resultSet.next()){
                Apply a = new Apply();
                a.setApplyid(resultSet.getInt("applyid"));
                a.setApplytime(resultSet.getTimestamp("applytime"));
                a.setApplyexplain(resultSet.getString("applyexplain"));
                a.setApplypicture(resultSet.getString("applypicture"));
                a.setApplystate(resultSet.getString("applystate"));
                User user=userDao.loadByUserId(resultSet.getInt("applyuserid"));
                a.setUser(user);
                Good good=goodDao.loadByGoodId(resultSet.getInt("applygoodid"));
                a.setGood(good);
                list.add(a);
            }
        }catch (SQLException e){
            throw new DaoException("数据封装出错。") ;
        }
        return list;
    }

}
